package com.junbao.message.infrastructure.dao;

import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.junbao.message.domain.model.NotifyMessage;
import com.junbao.message.domain.repository.MessageRepository;
import com.junbao.message.infrastructure.dto.NotifyMessageDto;
import com.junbao.message.infrastructure.page.DataQuereyCondition;
import com.junbao.message.infrastructure.util.JdbcUtils;

@SuppressWarnings("all")
public class MessageRepositoryImpl implements MessageRepository{
 
    private static final Logger LOGGER = LoggerFactory.getLogger(MessageRepositoryImpl.class);
    
    
    
    public int saveMessage(NotifyMessage notifyMessage) {
        NotifyMessageDto nd = new NotifyMessageDto(notifyMessage);
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "INSERT INTO \"message\" (\"uuid\", \"message_no\", \"message_squece\", \"notify_way\", "
                    + "\"notify_url\", \"notify_data_type\", \"notify_data\", \"confirm_count\", \"retry_max_count\", "
                    + "\"retry_count\", \"next_retry_time\", \"notify_status\", \"is_dead\", \"fail_remark\", \"confirm_way\","
                    + " \"confirm_req_url\", \"create_date\", \"update_date\", \"delete_flag\")"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            updateCount = queryRunner.update(sql, nd.getUuid(),nd.getMessageNo(),nd.getMessageSquece(),nd.getNotifyWay(),
                    nd.getNotifyUrl(),nd.getNotifyDataType(),nd.getNotifyData(),nd.getConfirmCount(),nd.getRetryMaxCount(),
                    nd.getRetryCount(),nd.getNextRetryTimeFormatt(),nd.getNotifyStatus(),nd.getIsDead(),nd.getFailRemark(),nd.getConfirmWay(),
                    nd.getConfirmReqUrl(),nd.getCreateDateFormatt(),nd.getUpdateDateFormatt(),nd.getDeleteFlag());
        } catch (Exception e) {
            LOGGER.error("新增消息信息失败！", e);
        }
        return updateCount;
    }
 
    
    public int updateMessage(NotifyMessage notifyMessage) {
        NotifyMessageDto nd = new NotifyMessageDto(notifyMessage);
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE \"message\" SET \"message_no\"=?, \"message_squece\"=?, \"notify_way\"=?, \"notify_url\"=?,"
                    + " \"notify_data_type\"=?, \"notify_data\"=?, \"confirm_count\"=?, \"retry_max_count\"=?, \"retry_count\"=?, "
                    + "\"next_retry_time\"=?, \"notify_status\"=?, \"is_dead\"=?, \"fail_remark\"=?, \"confirm_way\"=?,"
                    + " \"confirm_req_url\"=?, \"create_date\"=?, \"update_date\"=?, \"delete_flag\"=? WHERE \"uuid\" = ?";
            updateCount = queryRunner.update(sql, nd.getMessageNo(),nd.getMessageSquece(),nd.getNotifyWay(),
                    nd.getNotifyUrl(),nd.getNotifyDataType(),nd.getNotifyData(),nd.getConfirmCount(),nd.getRetryMaxCount(),
                    nd.getRetryCount(),nd.getNextRetryTimeFormatt(),nd.getNotifyStatus(),nd.getIsDead(),nd.getFailRemark(),nd.getConfirmWay(),
                    nd.getConfirmReqUrl(),nd.getCreateDateFormatt(),nd.getNowFormatt(),nd.getDeleteFlag(),nd.getUuid());
        } catch (Exception e) {
            LOGGER.error("新增消息信息失败！", e);
        }
        return updateCount;
    }
 
    
    public NotifyMessage queryMessageByMessageSquece(String messageSquece) {
        NotifyMessage notifyMessage = null;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "SELECT uuid as uuid,message_no as messageNo,message_squece as messageSquece,notify_way as notifyWay,"
                        +" notify_url as notifyUrl,notify_data_type as notifyDataType,notify_data as notifyData,confirm_count as confirmCount,"
                        +" retry_max_count as retryMaxCount,retry_count as retryCount,next_retry_time as nextRetryTime,notify_status as notifyStatus,is_dead as isDead,"
                        +" fail_remark as failRemark,confirm_way as confirmWay,confirm_req_url as confirmReqUrl,create_date as createDate,"
                        +" update_date as updateDate,delete_flag as deleteFlag FROM message WHERE message_squece = ? AND delete_flag = 0";
            NotifyMessageDto notifyMessageDto = queryRunner.query(sql, new BeanHandler<NotifyMessageDto>(NotifyMessageDto.class),messageSquece);
            notifyMessage = notifyMessageDto.buildNotifyMessage();
        } catch (Exception e) {
            LOGGER.error("根据消息序列号查询消息失败，消息序列号："+messageSquece, e);
        }
        return notifyMessage;
    }
 
    
    public List<NotifyMessage> queryWaitConfirmMessage(Date conditionTime) {
        List<NotifyMessage> notifyMessages = new LinkedList<NotifyMessage>();
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "SELECT uuid as uuid,message_no as messageNo,message_squece as messageSquece,notify_way as notifyWay,"
                        +" notify_url as notifyUrl,notify_data_type as notifyDataType,notify_data as notifyData,confirm_count as confirmCount,"
                        +" retry_max_count as retryMaxCount,retry_count as retryCount,next_retry_time as nextRetryTime,notify_status as notifyStatus,is_dead as isDead,"
                        +" fail_remark as failRemark,confirm_way as confirmWay,confirm_req_url as confirmReqUrl,create_date as createDate,"
                        +" update_date as updateDate,delete_flag as deleteFlag FROM message WHERE notify_status = 10 and is_dead = 20 AND delete_flag = 0 and create_date <= ?";
            List<NotifyMessageDto> notifyMessageDtos = queryRunner.query(sql, new BeanListHandler<NotifyMessageDto>(NotifyMessageDto.class),new Timestamp(conditionTime.getTime()));
            notifyMessages = NotifyMessageDto.buildNotifyMessages(notifyMessageDtos);
        } catch (Exception e) {
            LOGGER.error("查询待确认消息失败！", e);
        }
        return notifyMessages;
    }
 
    
    public int updateWaitConfirmMessageStatusToConfriming(Date conditionTime) {
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE message set notify_status = 12 , update_date = ?  WHERE notify_status = 10 and is_dead = 20 AND delete_flag = 0 and create_date <= ?";
            return queryRunner.update(sql, new Timestamp(new Date().getTime()),new Timestamp(conditionTime.getTime()));
        } catch (Exception e) {
            LOGGER.error("更新待确认消息失败！", e);
        }
        return 0;
    }
    
    
    public List<NotifyMessage> queryWaitSendMessage(Date conditionTime) {
        List<NotifyMessage> notifyMessages = new LinkedList<NotifyMessage>();
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "SELECT uuid as uuid,message_no as messageNo,message_squece as messageSquece,notify_way as notifyWay,"
                        +" notify_url as notifyUrl,notify_data_type as notifyDataType,notify_data as notifyData,confirm_count as confirmCount,"
                        +" retry_max_count as retryMaxCount,retry_count as retryCount,next_retry_time as nextRetryTime,notify_status as notifyStatus,is_dead as isDead,"
                        +" fail_remark as failRemark,confirm_way as confirmWay,confirm_req_url as confirmReqUrl,create_date as createDate,"
                        +" update_date as updateDate,delete_flag as deleteFlag FROM message WHERE notify_status = 20 and is_dead = 20 and create_date <= ?  and retry_count <= retry_max_count AND delete_flag = 0 ";
            List<NotifyMessageDto> notifyMessageDtos = queryRunner.query(sql, new BeanListHandler<NotifyMessageDto>(NotifyMessageDto.class),new Timestamp(conditionTime.getTime()));
            notifyMessages = NotifyMessageDto.buildNotifyMessages(notifyMessageDtos);
        } catch (Exception e) {
            LOGGER.error("查询待发送消息失败！", e);
        }
        return notifyMessages;
    }
    
    
    public int updateWaitSendMessageStatusToSending(Date conditionTime) {
        List<NotifyMessage> notifyMessages = new LinkedList<NotifyMessage>();
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "update message set notify_status = 20 , update_date = ? WHERE notify_status = 15 and is_dead = 20 and create_date <= ?  and retry_count <= retry_max_count AND delete_flag = 0 ";
            return queryRunner.update(sql,new Timestamp(new Date().getTime()),new Timestamp(conditionTime.getTime()));
        } catch (Exception e) {
            LOGGER.error("查询待发送消息失败！", e);
        }
        return 0;
    }
 
    
    public int updateStatusToWaitConfirm() {
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE message set notify_status = 10,update_date = ? WHERE notify_status = 5 and delete_flag = 0 AND update_date <(select CURRENT_TIMESTAMP::TIMESTAMP - INTERVAL '5 min')";
            updateCount = queryRunner.update(sql,new Timestamp(new Date().getTime()));
        } catch (Exception e) {
            LOGGER.error("新增消息信息失败！", e);
        }
        return updateCount;
    }
 
    
    public int updateMessageToDead() {
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE message set is_dead = 10,update_date = ?  WHERE notify_status in (15,50) and retry_count > retry_max_count  and delete_flag = 0";
            updateCount = queryRunner.update(sql,new Timestamp(new Date().getTime()));
        } catch (Exception e) {
            LOGGER.error("新增消息信息失败！", e);
        }
        return updateCount;
    }
 
    
    public int updateMessageToDead(NotifyMessage message) {
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE message set is_dead = 10,update_date = ? WHERE message_squece = ? and delete_flag = 0";
            updateCount = queryRunner.update(sql,new Timestamp(new Date().getTime()),message.getMessageSquece());
        } catch (Exception e) {
            LOGGER.error("新增消息信息失败！", e);
        }
        return updateCount;
    }
 
    
    public int queryWaitRemvalTotalCount(DataQuereyCondition condition) {
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "SELECT count(*) FROM message WHERE create_date < ?";
            Long messageDataCount = queryRunner.query(sql, new ScalarHandler<Long>(),new Timestamp(condition.getConditionTime().getTime()));
            updateCount = Integer.parseInt(messageDataCount.toString());
        } catch (Exception e) {
            LOGGER.error("查询待移除总记录数失败！", e);
        }
        return updateCount;
    }
 
    
    public List<NotifyMessage> queryWaitRemovalMessages(DataQuereyCondition condition) {
        List<NotifyMessage> notifyMessages = new LinkedList<NotifyMessage>();
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "SELECT uuid as uuid,message_no as messageNo,message_squece as messageSquece,notify_way as notifyWay,"
                        +" notify_url as notifyUrl,notify_data_type as notifyDataType,notify_data as notifyData,confirm_count as confirmCount,"
                        +" retry_max_count as retryMaxCount,retry_count as retryCount,next_retry_time as nextRetryTime,notify_status as notifyStatus,is_dead as isDead,"
                        +" fail_remark as failRemark,confirm_way as confirmWay,confirm_req_url as confirmReqUrl,create_date as createDate,"
                        +" update_date as updateDate,delete_flag as deleteFlag FROM message WHERE create_date < ? order by message_no ASC LIMIT ? OFFSET ?";
            List<NotifyMessageDto> notifyMessageDtos = queryRunner.query(sql, new BeanListHandler<NotifyMessageDto>(NotifyMessageDto.class),
                    new Timestamp(condition.getConditionTime().getTime()),condition.getPageSize(),condition.getStartIndex());
            notifyMessages = NotifyMessageDto.buildNotifyMessages(notifyMessageDtos);
        } catch (Exception e) {
            LOGGER.error("查询待发送消息失败！", e);
        }
        return notifyMessages;
    }
 
    
    public int addMessageToHistory(NotifyMessage notifyMessage) {
        NotifyMessageDto nd = new NotifyMessageDto(notifyMessage);
        int updateCount = 0;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "INSERT INTO \"message_history\" (\"uuid\", \"message_no\", \"message_squece\", \"notify_way\", "
                    + "\"notify_url\", \"notify_data_type\", \"notify_data\", \"confirm_count\", \"retry_max_count\", "
                    + "\"retry_count\", \"next_retry_time\", \"notify_status\", \"is_dead\", \"fail_remark\", \"confirm_way\","
                    + " \"confirm_req_url\", \"create_date\", \"update_date\", \"delete_flag\")"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            updateCount = queryRunner.update(sql, nd.getUuid(),nd.getMessageNo(),nd.getMessageSquece(),nd.getNotifyWay(),
                    nd.getNotifyUrl(),nd.getNotifyDataType(),nd.getNotifyData(),nd.getConfirmCount(),nd.getRetryMaxCount(),
                    nd.getRetryCount(),nd.getNextRetryTimeFormatt(),nd.getNotifyStatus(),nd.getIsDead(),nd.getFailRemark(),nd.getConfirmWay(),
                    nd.getConfirmReqUrl(),nd.getCreateDateFormatt(),nd.getUpdateDateFormatt(),nd.getDeleteFlag());
        } catch (Exception e) {
            LOGGER.error("新增消息信息到历史表失败！", e);
        }
        return updateCount;
    }
 
    
    public void deleteRemovaledMessageFromMessage(DataQuereyCondition condition) {
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "DELETE FROM message WHERE create_date < ?";
            queryRunner.update(sql,new Timestamp(condition.getConditionTime().getTime()));
        } catch (Exception e) {
            LOGGER.error("新增消息信息失败！", e);
        }
    }
    
    
    public NotifyMessage queryMessageByMessageNo(String messageNo) {
        NotifyMessage notifyMessage = null;
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "SELECT uuid as uuid,message_no as messageNo,message_squece as messageSquece,notify_way as notifyWay,"
                    +" notify_url as notifyUrl,notify_data_type as notifyDataType,notify_data as notifyData,confirm_count as confirmCount,"
                    +" retry_max_count as retryMaxCount,retry_count as retryCount,next_retry_time as nextRetryTime,notify_status as notifyStatus,is_dead as isDead,"
                    +" fail_remark as failRemark,confirm_way as confirmWay,confirm_req_url as confirmReqUrl,create_date as createDate,"
                    +" update_date as updateDate,delete_flag as deleteFlag FROM message WHERE message_no = ? AND delete_flag = 0";
            NotifyMessageDto notifyMessageDto = queryRunner.query(sql, new BeanHandler<NotifyMessageDto>(NotifyMessageDto.class),messageNo);
            if (notifyMessageDto != null) {
                notifyMessage = notifyMessageDto.buildNotifyMessage();
            }
        } catch (Exception e) {
            LOGGER.error("查询消息记录失败！", e);
        }
        return notifyMessage;
    }
    
    @Override
    public void messageStatusToWaitConfirmFromConfirmingUpdate() {
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE message set notify_status =10,update_date = ? WHERE notify_status =12 and delete_flag = 0";
            queryRunner.update(sql,new Timestamp(new Date().getTime()));
        } catch (Exception e) {
            LOGGER.error("更新确认中消息为待确认失败！", e);
        }
    }
    
    @Override
    public void messageStatusToWaitSendFromSendingUpdate() {
        try {
            QueryRunner queryRunner = new QueryRunner(JdbcUtils.getDataSource("message"));
            String sql = "UPDATE message set notify_status =15,update_date = ? WHERE notify_status =20 and delete_flag = 0";
            queryRunner.update(sql,new Timestamp(new Date().getTime()));
        } catch (Exception e) {
            LOGGER.error("更新发送中消息为待发送失败！", e);
        }
    }
 
}
